# -*- coding:utf-8 -*-

import struct,codecs,os
from win32com.client import Dispatch
from types import NoneType

def makedic():
    dic={}
    tbl=codecs.open('in.tbl','r+b','utf_16')
    for line in tbl:
        line_split=line.replace('\r\n','').split(u'=')
        dic[line_split[1]]=line_split[0].lower()
    tbl.close()
    return dic

mydic=makedic()

#写入单字节
def bytewrite(j):
    return chr(int(mydic[string[j]],16))

#写入unicode字符
def wordwrite(j):
    return chr(int(mydic[string[j]][:2],16))+chr(int(mydic[string[j]][2:4],16))

excel = Dispatch("Excel.Application")
d1 = excel.Workbooks.Open(os.getcwd()+os.sep+'LOC_0uk.tx.xls.xls')
sheet = d1.Sheets(1)
target=open('LOC_0uk.tx','wb')
target.seek(0x81b)

offset_list=[]
for i in xrange(0,0x81b-2,2):
    string=sheet.Cells(i/2+2, 2).Value
    if isinstance(string,float):
        string='%d'%string
        offset_list.append(target.tell())
    elif isinstance(string,NoneType):
        string=''
        offset_list.append(0xffff)
    else:
        offset_list.append(target.tell())

    print string
    j=0
    while j<len(string):

        #如果读取的是回车符0d
        if ord(string[j])==10:

            #写入换行符
            target.write('\x0a')
            j+=1

        #如果字符在字典里面，则导入
        elif string[j] in mydic:

            if len(mydic[string[j]])==4:
                target.write(wordwrite(j))

            if len(mydic[string[j]])==2:
                target.write(bytewrite(j))
            j+=1
        else:
            print 'the word',repr(string[j]),'not in dic'
            j+=1
            continue
    if len(string)>0:
        target.write('\x00\x04')

target.seek(0)
for offset in offset_list:
    target.write(struct.pack('H',offset))
target.write('\x04')
target.close()
excel.Quit()
